package com.darco.darcoapp;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import com.darco.darcoapp.db.DarcoData;

import eneter.messaging.endpoints.typedmessages.TypedResponseReceivedEventArgs;

import DARCOShared.requests.GetCardFromQRScanRequest;
import DARCOShared.requests.GetCardListByOwnerRequest;
import DARCOShared.responses.GetCardFromQRScanResponse;
import DARCOShared.responses.GetCardListByOwnerResponse;
import DARCOShared.responses.ResponseBase;
import DARCOShared.responses.ResponseType;
import DARCOShared.responses.ResponseWrapper;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import static DARCOShared.utils.Constants.*;

public class Main_Activity extends MessagingActivity implements OnClickListener{
	private DarcoData d;
	private MessagingManager mm;
	private Bundle extra=null;
	private ContentValues account=null;
	private ContentValues system=null;
	
	private static final int RECEIVER_FROM_BLUETOOTH_REQUEST_CODE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_);

		d= new DarcoData(this);

		//click listener for all buttons
		View info_button = findViewById(R.id.main_accountinfo_button);
		info_button.setOnClickListener(this);

		View list_button = findViewById(R.id.main_list_button);
		list_button.setOnClickListener(this);

		View qrscan_button = findViewById(R.id.main_qrscan_button);
		qrscan_button.setOnClickListener(this);
		
		findViewById(R.id.main_btReceive_button).setOnClickListener(this);
		findViewById(R.id.main_updatePosition_button).setOnClickListener(this);


		extra=getIntent().getExtras();
		if(extra!=null){
			account=((ContentValues) extra.get("account"));
			system= ((ContentValues) extra.get("system"));

			byte[] image_avatar = account.getAsByteArray(ACCOUNT_AVATAR);
			String account_name = account.getAsString(ACCOUNT_USERNAME);
			TextView account_greatings=(TextView) findViewById(R.id.main_greatings_textView);
			ImageView avatar = (ImageView) findViewById(R.id.main_avatar_imageView);


			if(image_avatar!=null){
				//account_greatings.setCompoundDrawables(Drawable.createFromStream(new ByteArrayInputStream(image_avatar), "avatar"), null,null,null);
				Bitmap bmp=BitmapFactory.decodeByteArray(image_avatar,0,image_avatar.length);
				if(bmp!=null){
					avatar.setImageBitmap(bmp);
				}
			}
			else
				Toast.makeText(this, "avatar null", Toast.LENGTH_SHORT).show();

			if(account_name!=null)
				account_greatings.setText("Hi, "+account_name);

		}
		else{
			Toast.makeText(this, "Error: no account data found", Toast.LENGTH_LONG).show();
			//back to login
			//startActivity(new Intent(this,Login_Activity.class));
		}


	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_, menu);
		return true;
	}

	@Override
	public void onClick(View arg0) {
		switch(arg0.getId()){
		case R.id.main_accountinfo_button:
			Intent i_info= new Intent(this,AccountInfo_Activity.class);
			i_info.putExtra("account", account);
			i_info.putExtra("system", system);
			startActivity(i_info);
			break;
		case R.id.main_list_button:
			GetCardListByOwnerRequest req= new GetCardListByOwnerRequest(account.getAsString(ACCOUNT_EMAIL));
			onPerformRequest(req);
			//TODO
			break;
		case R.id.main_qrscan_button:
			Intent i1 = new Intent(this,ScanActivity.class);
			i1.putExtra("account",account);
			i1.putExtra("system", system);
			startActivity(i1);
			break;
		case R.id.main_btReceive_button:
			Intent i_receive = new Intent(this,BluetoothManager.class);
			i_receive.putExtra("mode", BluetoothManager.INTENT_LISTEN_AND_RECEIVE);
			i_receive.putExtra("system", getIntent().getExtras().getParcelable("system"));
			i_receive.putExtra("account", getIntent().getExtras().getParcelable("account"));
			startActivityForResult(i_receive, RECEIVER_FROM_BLUETOOTH_REQUEST_CODE);
			break;
		case R.id.main_updatePosition_button:
			Intent i3 = new Intent(this, UpdateLocation_Activity.class);
			i3.putExtra("system", getIntent().getExtras().getParcelable("system"));
			i3.putExtra("account", getIntent().getExtras().getParcelable("account"));
			startActivityForResult(i3, 0);
			break;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if ((keyCode == KeyEvent.KEYCODE_BACK))
		{
			//onDestroy();
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			//intent.putExtra("CLOSE_IMMEDIATELY", true);

			startActivity(intent);
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.main_menu_about:
			return menuAbout();
		case R.id.main_menu_settings:
			Intent i1= new Intent(this,Settings_Activity.class);
			i1.putExtra("system", system);
			i1.putExtra("account", account);
			startActivity(i1);	        	
			return true;
		case R.id.main_menu_logout:
			//azzero i campi locali
			account.clear();
			system.clear();
			finish(); //termino l'activity main di main
			//chiamo la funzione di logout
			return menuLogout();
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	void onPerformRequest(GetCardListByOwnerRequest req){
		//inizializzazione ...
		mm = new MessagingManager();
		mm.ConnectToServer(this); //mi connetto al server e mi iscrivo alle risposte
		mm.SendRequest(req, this); //invia una richiesta di info carta
		//qui sara necessario mostrare un popup di attesa, tipo "caricamento in corso" o roba simile
		//Toast.makeText(getApplicationContext(), "Request sent!", Toast.LENGTH_SHORT).show();
		showLoadingDialog("Wait for User's Card List");
	}
	@Override
	void onResponseReceived(Object sender,
			TypedResponseReceivedEventArgs<ResponseWrapper> e) {
		ResponseBase respbase = e.getResponseMessage().getResponse();
		ResponseType resptype=respbase.getResponseType();

		switch(resptype){
		case GetCardListByOwner:
			GetCardListByOwnerResponse resplist= (GetCardListByOwnerResponse) respbase;
			if(resplist.err==false){
				Vector<HashMap<String, Object>> cardList = resplist.cardList;
				Log.d("response","card list received :"+cardList.size()+" cards");
				if(cardList.size()>=1){
					Intent i = new Intent(this,List_Activity.class);
					Pair<ArrayList<ContentValues>, ArrayList<ContentValues>> data=makeCardListContentValues(cardList);
					i.putExtra("cardList", data.second);
					i.putExtra("uniqueList", data.first);
					i.putExtra("account", account);
					i.putExtra("system", system);
					Log.d("makeCardList","card list -> content");
					startActivity(i);
				}
				else{
					showNoCardAlert(0);
				}
			}
			else{
				Toast.makeText(this, "Error: "+resplist.error, Toast.LENGTH_LONG).show();
			}
			hideLoadingDialog();
			break;
		default:
			break;
		}
		// TODO Auto-generated method stub

	}

	public Pair<ArrayList<ContentValues>, ArrayList<ContentValues>> makeCardListContentValues(Vector<HashMap<String, Object>> list){
		final int numElem= list.size();

		ArrayList<ContentValues> uni= new ArrayList<ContentValues>();
		ArrayList<ContentValues> crd= new ArrayList<ContentValues>();

		ContentValues unique; 
		ContentValues card;

		//SQLiteDatabase db= getWritableDatabase();
		HashMap<String, Object> aux;
		//prima creo i content values
		for(int i=0; i<numElem; i++){
			//gestione e inserimento di una carta nel db locale
			aux=list.get(i);
			unique = new ContentValues();
			card = new ContentValues();

			//inserimento dati carta
			card.put(CARD_SN,((String) aux.get(CARD_SN)));
			card.put(CARD_NAME,((String) aux.get(CARD_NAME)));
			card.put(CARD_STATS,((String) aux.get(CARD_STATS)));
			card.put(CARD_SPECIAL,((String) aux.get(CARD_SPECIAL)));
			Long catId = (Long) aux.get(CARD_CATEGORY);
			card.put(CARD_CATEGORY,catId);
			card.put(CARD_CATEGORY_NAME,((String) aux.get(CARD_CATEGORY_NAME)));
			Long subId = ((Long) aux.get(CARD_SUBCATEGORY));
			card.put(CARD_SUBCATEGORY,subId);
			card.put(CARD_SUBCATEGORY_NAME,((String) aux.get(CARD_SUBCATEGORY_NAME)));

			card.getAsInteger(CARD_CATEGORY);

			card.put(CARD_PREVIEW,((byte[]) aux.get(CARD_PREVIEW)));
			//card.put(CARD_IMAGE,null);

			//inserimento fati unique
			unique.put(UNIQUECARD_SN,((String) aux.get(UNIQUECARD_SN)));
			unique.put(UNIQUECARD_ID,((String) aux.get(UNIQUECARD_ID)));
			unique.put(UNIQUECARD_AUTENTICATED,((Long) aux.get(UNIQUECARD_AUTENTICATED)));
			unique.put(UNIQUECARD_ACTUALOWNER,((String) aux.get(UNIQUECARD_ACTUALOWNER)));
			unique.put(UNIQUECARD_FIRSTOWNER, ((String) aux.get(UNIQUECARD_FIRSTOWNER)));
			unique.put(UNIQUECARD_FIRSTAUTH, ((String) aux.get(UNIQUECARD_FIRSTAUTH)));

			uni.add(unique);
			crd.add(card);

		}
		return new Pair<ArrayList<ContentValues>,ArrayList<ContentValues>>(uni, crd);
	}

	private void showNoCardAlert(final int why){
		hideLoadingDialog();
		AlertDialog dialogBox = new AlertDialog.Builder(this).create();
		dialogBox.setTitle("Card List");
		if(why==0)
			dialogBox.setMessage("Your account is not associate with any authenticated card. try to autenticate some cards with QR Scan function ;)");
		dialogBox.setButton("Ok",  new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				//return to trading activity
				//finishActivity(why);
				
			}
		});
		dialogBox.show();
	}
}
